package com.bicon.botu.mall.goods.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bicon.botu.commons.constants.MallConstants;
import com.bicon.botu.mall.goods.commons.GoodsConstants;
import com.bicon.botu.mall.goods.service.IClassAttributeItemService;
import com.bicon.botu.mall.goods.service.IClassAttributeService;
import com.bicon.botu.mall.goods.service.IClassficationService;
import com.bicon.botu.mall.goods.service.IProductService;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.mall.goods.entity.ClassAttribute;
import com.bicon.botu.mall.goods.entity.ClassAttributeItem;
import com.bicon.botu.mall.goods.entity.Classfication;
import com.bicon.botu.mall.goods.entity.Product;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 商品分类
 * @author dsp
 * @since 2017-07-19
 */
@RestController
@RequestMapping("/V0.0.1/classfication")
public class ClassficationController extends BaseController{

    @Autowired
    private IClassficationService iClassficationService; //商品分类

    @Autowired
    private IClassAttributeService iClassAttributeService;  //商品规格

    @Autowired
    private IClassAttributeItemService iClassAttributeItemService;  //商品规格项

    @Autowired
    private IProductService iProductService;        //商品

    /**
     * 商品分类新增
     * @param classfication
     * @return
     */
    @RequestMapping(value="save",method = RequestMethod.POST)
    public BaseResult save(Classfication classfication){
        if(classfication!=null){
            //商品分类名称、分类ParentID、级别 参数校验
            if(StringUtils.isNotBlank(classfication.getName()) && StringUtils.isNotBlank(classfication.getParentId())
                    && classfication.getLevel() !=null){
                //初始化主键、创建时间等
                classfication.preInsert();
                //查询父节点下所有子集数量
                int childCount=iClassficationService.selectCount(new EntityWrapper<Classfication>().eq("parent_id",classfication.getParentId()));
                //设置排序字段
                classfication.setRank(childCount==0?1:(childCount+1));
                //获取父节点对象，path:父节点对象Path+"#"+新增对象ID
                Classfication parentClassfication=iClassficationService.selectById(classfication.getParentId());
                if(parentClassfication!=null){
                    classfication.setPath(parentClassfication.getPath()+"#"+classfication.getId());
                }else{
                    classfication.setPath(classfication.getId());
                }
                boolean result=iClassficationService.insertOrUpdate(classfication);
                if(result){
                    return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200);
                }else{
                    return sendResult(GoodsConstants.RESPONSE_CODE_600,GoodsConstants.RESPONSE_MESSAGE_600);
                }
            }else{
                return sendResult(GoodsConstants.RESPONSE_CODE_400,GoodsConstants.RESPONSE_MESSAGE_400);
            }
        }else{
            return sendResult(GoodsConstants.RESPONSE_CODE_400,GoodsConstants.RESPONSE_MESSAGE_400);
        }
    }

    /**
     * 商品分类修改
     * @param classfication
     * @return
     */
    @RequestMapping(value="modify",method = RequestMethod.POST)
    public BaseResult modify(Classfication classfication){
        boolean result=false;
        if(classfication!=null){
            //商品分类名称、分类ParentID、级别 参数校验
            if(StringUtils.isNotBlank(classfication.getId())){
                //设置修改时间
                classfication.setUpdateDate(new Date());
                //判断是否一级或二级分类修改“是否显示”，如果不显示，则子级也应该批量修改为不显示
                if(classfication.getLevel()!=null && classfication.getLevel()<3
                        && StringUtils.isNotBlank(classfication.getIsShow())
                        && GoodsConstants.ISSHOW_OFF_MARK.equals(classfication.getIsShow())){
                    //设置修改参数
                    Classfication entity=new Classfication();
                    entity.setIsShow(GoodsConstants.ISSHOW_OFF_MARK);
                    //设置查询条件
                    EntityWrapper<Classfication> entityWrapper=new EntityWrapper<>();
                    entityWrapper.like("path",classfication.getId());
                    result=iClassficationService.update(entity,entityWrapper);
                }else{
                    result=iClassficationService.insertOrUpdate(classfication);
                }
                if(result){
                    return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200);
                }else{
                    return sendResult(GoodsConstants.RESPONSE_CODE_600,GoodsConstants.RESPONSE_MESSAGE_600);
                }
            }else{
                return sendResult(GoodsConstants.RESPONSE_CODE_400,GoodsConstants.RESPONSE_MESSAGE_400);
            }
        }else{
            return sendResult(GoodsConstants.RESPONSE_CODE_400,GoodsConstants.RESPONSE_MESSAGE_400);
        }
    }

    /**
     * 商品分类删除
     * @param id
     * @return
     */
    @RequestMapping(value="delete/{id}",method = RequestMethod.GET)
    public BaseResult delete(@PathVariable("id") String id){
        boolean result=false;
        //在商品列表中检测该分类节点是否被使用
        int count=iProductService.selectCount(new EntityWrapper<Product>().like("category_id",id).eq("logic_delete",GoodsConstants.DEL_LOGIC_NORMAL));
        if(count>0){
            return sendResult(MallConstants.RESPONSE_CODE_605,MallConstants.RESPONSE_MESSAGE_605);
        }else{
            //判断是否有子节点
            int childCount=iClassficationService.selectCount(new EntityWrapper<Classfication>().eq("parent_id",id));
            if(childCount>0){
                iClassficationService.delete(new EntityWrapper<Classfication>().eq("parent_id",id));
            }
            result=iClassficationService.deleteById(id);
            //判断分类节点、
            if(result){
                return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200);
            }else{
                return sendResult(GoodsConstants.RESPONSE_CODE_600,GoodsConstants.RESPONSE_MESSAGE_600);
            }
        }
    }

    /**
     * 查询一个层级下所有集合
     * 查询一个节点的所有子节点
     * 查询一个层级下，parentId相同的集合
     * @param level
     * @param pid
     * @return
     */
    @RequestMapping(value="findByLevelAndId",method =RequestMethod.POST)
    public BaseResult findByLevelAndId(@RequestParam(defaultValue = "") String level, @RequestParam(defaultValue = "") String pid,
                                       @RequestParam(defaultValue = "",required = false) String name,
                                       @RequestParam(defaultValue = "",required = false) String isShow){
        boolean mark=false;
        EntityWrapper<Classfication> entityWrapper=new EntityWrapper<>();
        if(StringUtils.isNotBlank(level)){
            mark=true;
            entityWrapper.eq("level",level);
        }
        if(StringUtils.isNotBlank(pid)){
            mark=true;
            entityWrapper.eq("parent_id",pid);
        }
        if(StringUtils.isNotBlank(name)){
            mark=true;
            entityWrapper.eq("name",name);
        }
        if(StringUtils.isNotBlank(isShow)){
            mark=true;
            entityWrapper.eq("is_show",isShow);
        }
        entityWrapper.orderBy("rank");
        if(mark){
            List<Classfication> classficationList=iClassficationService.selectList(entityWrapper);
            return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200,classficationList);
        }else{
            return sendResult(GoodsConstants.RESPONSE_CODE_400,GoodsConstants.RESPONSE_MESSAGE_400);
        }
    }

    /**
     * 根据商品分类ID 查询分类下的商品规格及规格项
     * @param id
     * @return
     */
    @RequestMapping(value="findAttributItemByClassId/{id}",method=RequestMethod.GET)
    public BaseResult findAttributItemByClassId(@PathVariable("id") String id){
        //用于返回数据JSON数组
        JSONArray jsonArray=new JSONArray();
        //查询商品规格
        ClassAttribute classAttribute=iClassAttributeService.selectOne(new EntityWrapper<ClassAttribute>().eq("class_id",id));
        if(classAttribute!= null){
            //查询一级规格-对应规格项
            EntityWrapper<ClassAttributeItem> entityWrapper=new EntityWrapper<>();
            entityWrapper.eq("attribute_id",classAttribute.getId());
            entityWrapper.eq("attribute_mark",GoodsConstants.FIRST_CLASSATTRIBUT_MARK);
            entityWrapper.orderBy("rank",true);
            List<ClassAttributeItem> classAttributeItems=iClassAttributeItemService.selectList(entityWrapper);
            if(classAttributeItems!= null && classAttributeItems.size()>0){
                JSONObject jsonObject=new JSONObject();
                //规格
                jsonObject.put("classAttribute",classAttribute);
                //规格项值
                jsonObject.put("classAttributeItems",classAttributeItems);
                jsonArray.add(jsonObject);
            }
            //查询二级规格-对应规格项
            entityWrapper=new EntityWrapper<>();
            entityWrapper.eq("attribute_id",classAttribute.getId());
            entityWrapper.eq("attribute_mark",GoodsConstants.SECOND_CLASSATTRIBUT_MARK);
            entityWrapper.orderBy("rank",true);
            classAttributeItems=iClassAttributeItemService.selectList(entityWrapper);
            if(classAttributeItems!= null && classAttributeItems.size()>0){
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("classAttribute",classAttribute);
                jsonObject.put("classAttributeItems",classAttributeItems);
                jsonArray.add(jsonObject);
            }
        }
        return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200,jsonArray);
    }

    /**
     *  根据分类id查询分类名称
     * @param id
     * @return
     */
    @RequestMapping("getClassName")
    public BaseResult getClassName(@RequestParam(value = "id")String id){
       Classfication fication= iClassficationService.selectById(id);
       return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200,fication);
    }

    /**
     * 根据三级分类Path，获得分类名称拼接字符串
     * 一级分类-二级分类-三级分类
     * @param path
     * @return
     */
    @RequestMapping(value = "findClaNameStringByPath",method = RequestMethod.POST)
    public BaseResult findClaNameStringByPath(@RequestParam(defaultValue = "") String path){
        //暂取分类名称
        StringBuffer stringBuffer=new StringBuffer();
        Classfication classfication=null;
        if(StringUtils.isNotBlank(path)){
            String[] idArray=path.split("#");
            //获得一级分类名称
            if(idArray.length>1 && StringUtils.isNotBlank(idArray[1])){
                classfication=iClassficationService.selectById(idArray[1]);
                stringBuffer.append(classfication.getName());
            }
            //获得二级分类名称
            if(idArray.length>2 && StringUtils.isNotBlank(idArray[2])){
                classfication=null;
                stringBuffer.append("-");
                classfication=iClassficationService.selectById(idArray[2]);
                stringBuffer.append(classfication.getName());
            }
            //获得二级分类名称
            if(idArray.length>3 && StringUtils.isNotBlank(idArray[3])){
                classfication=null;
                stringBuffer.append("-");
                classfication=iClassficationService.selectById(idArray[3]);
                stringBuffer.append(classfication.getName());
            }
            return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200,stringBuffer.toString());
        }else{
            return sendResult(GoodsConstants.RESPONSE_CODE_400,GoodsConstants.RESPONSE_MESSAGE_400);
        }
    }

    /**
     * 批量排序接口
     * @param rankJson
     * @return
     */
    @RequestMapping(value = "batchUpdateRank",method = RequestMethod.POST)
    public BaseResult batchUpdateRank(@RequestParam(defaultValue = "") String rankJson){
        //校验参数JSON是否为空
        if(StringUtils.isNotBlank(rankJson)){
            //JSON 转规格项集合
            List<Classfication> classficationList= JSONArray.parseArray(rankJson,Classfication.class);
            if(classficationList!=null && classficationList.size()>0){
                //批量操作修改数据排序字段
                boolean result=iClassficationService.updateBatchById(classficationList);
                if(result){
                    return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200);
                }else{
                    return sendResult(GoodsConstants.RESPONSE_CODE_600,GoodsConstants.RESPONSE_MESSAGE_600);
                }
            }else {
                return sendResult(GoodsConstants.RESPONSE_CODE_400,GoodsConstants.RESPONSE_MESSAGE_400);
            }
        }else{
            return sendResult(GoodsConstants.RESPONSE_CODE_400,GoodsConstants.RESPONSE_MESSAGE_400);
        }
    }
}
